﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace MorphismTheme
{
    public class InputNumber : TextBox
    {
        public double Step
        {
            get => (double)GetValue(StepProperty);
            set => SetValue(StepProperty, value);
        }

        public static readonly DependencyProperty StepProperty =
            DependencyProperty.Register(nameof(Step), typeof(double), typeof(InputNumber), new PropertyMetadata(0.1));

        public int CornerRadius
        {
            get => (int)GetValue(CornerRadiusProperty);
            set => SetValue(CornerRadiusProperty, value);
        }

        public static readonly DependencyProperty CornerRadiusProperty =
            DependencyProperty.Register(nameof(CornerRadius), typeof(int), typeof(InputNumber), new PropertyMetadata(0));


        public double Minimum
        {
            get { return (double)GetValue(MinimumProperty); }
            set { SetValue(MinimumProperty, value); }
        }
        public static readonly DependencyProperty MinimumProperty =
            DependencyProperty.Register(nameof(Minimum), typeof(double), typeof(InputNumber), new PropertyMetadata(0.0));

        static InputNumber()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(InputNumber), new FrameworkPropertyMetadata(typeof(InputNumber)));
        }

        public InputNumber()
        {
            InputMethod.SetIsInputMethodEnabled(this, false);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            Button DeButton = (Button)this.Template.FindName("DeButton", this);
            Button InButton = (Button)this.Template.FindName("InButton", this);
            DeButton.PreviewMouseLeftButtonDown += DeButton_MouseLeftButtonDown;
            InButton.PreviewMouseLeftButtonDown += InButton_MouseLeftButtonDown;
        }

        private void DeButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!String.IsNullOrEmpty(this.Text))
            {
                this.Text = Math.Round(double.Parse(this.Text), 3) - Step < Minimum ? Minimum + "" : Math.Round(double.Parse(this.Text),3) - Step + "";
                this.SelectionStart = this.Text.Length;
            }
            else
            {
                this.Text = Minimum + "";
                this.SelectionStart = this.Text.Length;
            }
        }

        private void InButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!String.IsNullOrEmpty(this.Text))
            {
                this.Text = double.Parse(this.Text) + Step + "";
                this.SelectionStart = this.Text.Length;
            }
            else
            {
                this.Text = Minimum + "";
                this.SelectionStart = this.Text.Length;
            }
        }
    }
}
